package com.sn.author.monitor.msg;

import com.alibaba.fastjson.JSON;
import com.sn.author.common.context.SpringContext;
import com.sn.author.common.enums.TaskTypeEnum;
import com.sn.author.common.exception.SystemException;
import com.sn.author.domain.entity.TaskMessage;
import com.sn.author.monitor.msg.entity.TaskPushMessage;
import com.sn.author.monitor.msg.eventModel.TaskMessageEvent;
import com.sn.author.service.dao.TaskMessageService;
import com.sn.author.service.impl.WebSocket;
import com.sn.author.utils.BeanUtils;
import com.sn.author.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * @Author xiaom
 * @Date 2020/9/25 15:06
 * @Version 1.0.0
 * @Description <>
 **/
@Component
@Slf4j
public class TaskMessageListener extends Listener {

    @Autowired
    private TaskMessageService taskMessageService;

    @EventListener
    public void onApplicationEvent(TaskMessageEvent event){
        //保存任务执行情况
        save(event.getTaskPushMessage());
        //推送给前端
        try {
            SpringContext.getBean(WebSocket.class).sendMessage(JSON.toJSONString(event.getTaskPushMessage()));
        } catch (IOException e) {
            log.error("【"+TaskTypeEnum.match(event.getTaskPushMessage().getTaskType()).get().getDesc() + "】 推送任务执行消息失败");
            e.printStackTrace();
        }
    }

    private void save(TaskPushMessage taskPushMessage) {
        TaskMessage taskMessage = BeanUtils.transformFrom(taskPushMessage,TaskMessage.class);
        if(taskMessage == null){
            throw new SystemException();
        }
        taskMessage.setDate(DateUtils.formatYMDHMS(new Date()));
        taskMessageService.saveEntity(taskMessage);
    }
}
